﻿using System;
using QuantBox;
using SmartQuant;

namespace QdpDemo
{
    public class TradingTestStrategy : Strategy
    {
        private Order? _openOrder;
        private Trade? _lastTrade;

        public TradingTestStrategy(Framework framework, string name) 
            : base(framework, name)
        {
        }

        protected override void OnOrderRejected(Order order)
        {
            base.OnOrderRejected(order);
        }

        protected override void OnOrderDone(Order order)
        {
            _openOrder = null;
        }

        protected override void OnLevel2(Instrument instrument, Level2Snapshot snapshot)
        {
            
        }
        
        protected override void OnTrade(Instrument instrument, Trade trade)
        {
            if (_openOrder != null) {
                if ((DateTime.Now - _openOrder.DateTime).TotalSeconds > 2) {
                    Cancel(_openOrder);
                    _openOrder.DateTime = DateTime.Now;
                }
                return;
            }
            if (_lastTrade != null) {
                var position = this.GetPosition(instrument)!;
                if (_lastTrade.Price >= trade.Price) {
                    //position.ShortAvailable;
                    _openOrder = position.ShortAvailable > 0
                        ? BuyLimitOrder(instrument, 1, trade.Price).CloseToday().Send()
                        : BuyLimitOrder(instrument, 1, trade.Price).Open().Send();
                }
                else if (_lastTrade.Price < trade.Price) {
                    _openOrder = position.LongAvailable > 0
                        ? SellLimitOrder(instrument, 1, trade.Price).CloseToday().Send()
                        : SellLimitOrder(instrument, 1, trade.Price).Open().Send();
                }
            }
            _lastTrade = trade;
        }
    }
}